package com.tbi.graphcolouring.algorithmconfiguration.selector;

import java.util.ArrayList;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;

import com.tbi.algorithm.configuration.ISelector;
import com.tbi.graphcolouring.AlgorithmSettings;
import com.tbi.graphcolouring.PopulationEntity;
import com.tbi.graphcolouring.utils.Random;

public class TournamentSelector implements ISelector {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void selection(List population) {
		ArrayList<PopulationEntity> newPopulation = new ArrayList<>();
		int populationSize = population.size();
		
		for(int i = 0; i<populationSize*AlgorithmSettings.SELECTION_FACTOR; i++){
			PopulationEntity entity = tournament(population, populationSize - i); 
			population.remove(entity);
			newPopulation.add(entity);
		}
		
		population.clear();
		population.addAll(newPopulation);
	}
	
	@SuppressWarnings("rawtypes")
	private List tournamentGroup = new ArrayList<>(AlgorithmSettings.TOURNAMENT_GROUP_SIZE);
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private PopulationEntity tournament(List population, int populationSize){
		for (int i = 0; i < AlgorithmSettings.TOURNAMENT_GROUP_SIZE; i++) {
			tournamentGroup.add(population.get((int)Random.uniform(0, populationSize - 1)));
		}
		Collections.sort(tournamentGroup);
		
		PopulationEntity winner = (PopulationEntity) tournamentGroup.get(0);
		tournamentGroup.clear();
		
		return winner;
	}

}
